<template>
  <el-dialog
    v-model="visible"
    title="护理记录"
    width="70%"
    :close-on-click-modal="false"
    @close="closeDialog"
  >
    <div class="app-container">
      <div class="search-bar">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          <el-form-item label="日期" prop="serviceDate">
            <el-date-picker
              v-model="queryParams.serviceDate"
              type="daterange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD"
              style="width: 250px"
            />
          </el-form-item>
          <el-form-item label="护理人" prop="keywords">
            <el-input
              v-model="queryParams.keywords"
              placeholder="护理人"
              clearable
              @keyup.enter="handleQuery()"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">
              <template #icon>
                <Search />
              </template>
              搜索
            </el-button>
            <el-button @click="handleResetQuery">
              <template #icon>
                <Refresh />
              </template>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-card shadow="never">
        <div class="mb-10px">
          <el-button v-hasPerm="['system:wxKf:add']" type="success" @click="handleOpenDialog()">
            <template #icon>
              <Plus />
            </template>
            新增
          </el-button>
          <el-button
            v-hasPerm="['system:wxKf:delete']"
            type="danger"
            :disabled="removeIds.length === 0"
            @click="handleDelete()"
          >
            <template #icon>
              <Delete />
            </template>
            删除
          </el-button>
        </div>

        <el-table
          ref="dataTableRef"
          v-loading="loading"
          :data="pageData"
          highlight-current-row
          border
          @selection-change="handleSelectionChange"
        >
          <!-- 日期 护理内容 剩余次数   金额   护理人 备注  顾客签字 -->
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column type="index" label="序号" width="80" align="center" />
          <el-table-column
            key="serviceDate"
            label="日期"
            prop="serviceDate"
            width="150"
            align="center"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            key="content"
            label="护理内容"
            prop="content"
            min-width="250"
            align="center"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            key="remainNum"
            label="剩余次数"
            prop="remainNum"
            width="120"
            align="center"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            key="amount"
            label="金额"
            prop="amount"
            width="120"
            align="center"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            key="nurseName"
            label="护理人"
            prop="nurseName"
            min-width="150"
            align="center"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            key="remark"
            label="备注"
            prop="remark"
            min-width="200"
            align="center"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            key="signature"
            label="顾客签字"
            prop="signature"
            min-width="150"
            align="center"
            :show-overflow-tooltip="true"
          >
            <template #default="scope">
              <img
                v-if="scope.row.signature"
                :src="scope.row.signature"
                alt="顾客签字"
                style="width: 100px; height: auto"
              />
              <span v-else></span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" align="center" width="150">
            <template #default="scope">
              <el-button type="primary" size="small" link @click="handleViewDialog(scope.row.id)">
                <template #icon>
                  <View />
                </template>
                查看
              </el-button>
              <el-button
                v-hasPerm="['system:wxKf:edit']"
                type="primary"
                size="small"
                link
                @click="handleOpenDialog(scope.row.id)"
              >
                <template #icon>
                  <Edit />
                </template>
                编辑
              </el-button>
              <el-button
                v-hasPerm="['system:wxKf:delete']"
                type="danger"
                size="small"
                link
                @click="handleDelete(scope.row.id)"
              >
                <template #icon>
                  <Delete />
                </template>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-if="total > 0"
          v-model:total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handleQuery()"
        />
      </el-card>

      <!-- 客户档案表单弹窗 -->
      <el-dialog
        v-model="dialog.visible"
        :title="dialog.title"
        width="700px"
        :close-on-click-modal="false"
        @close="handleCloseDialog"
      >
        <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="80px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="日期" prop="serviceDate">
                <el-date-picker
                  v-model="formData.serviceDate"
                  type="date"
                  placeholder="请选择日期"
                  value-format="YYYY-MM-DD"
                  style="width: 200px"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="护理人" prop="nurseName">
                <el-input v-model="formData.nurseName" placeholder="请输入护理人" maxlength="150" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="护理内容" prop="content">
            <el-input v-model="formData.content" placeholder="请输入护理内容" maxlength="150" />
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label="剩余次数" prop="remainNum">
                <el-input-number
                  v-model="formData.remainNum"
                  :min="0"
                  :controls="false"
                  style="width: 200px"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="金额" prop="amount">
                <el-input v-model="formData.amount" placeholder="请输入金额" maxlength="64" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="formData.remark"
              type="textarea"
              placeholder="请输入备注"
              :rows="4"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="客户签名" prop="signature">
            <div v-if="formData.signature && !reSignture">
              <img :src="formData.signature" alt="顾客签字" />
              <el-button type="primary" @click="handleReSignature">重新签名</el-button>
            </div>
            <SignatureCanvas
              v-else
              ref="signatureRef"
              :show-save-button="false"
              @signature-change="handleSignatureChange"
            />
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="handleSubmit" :disabled="loading">确 定</el-button>
            <el-button @click="handleCloseDialog">取 消</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 客户档案表单弹窗 -->
      <el-dialog
        v-model="dialog2.visible"
        :title="dialog2.title"
        width="700px"
        :close-on-click-modal="false"
        @close="handleCloseDialog1"
      >
        <el-form ref="dataFormRef1" :model="formData" label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="日期：" prop="serviceDate">
                {{ formData.serviceDate }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="护理人：" prop="nurseName">
                {{ formData.nurseName }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="护理内容：" prop="content">
            {{ formData.content }}
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label="剩余次数：" prop="remainNum">
                {{ formData.remainNum }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="金额：" prop="amount">
                {{ formData.amount }}
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="备注：" prop="remark">
            {{ formData.remark }}
          </el-form-item>

          <el-form-item label="客户签名：" prop="signature">
            <img :src="formData.signature" alt="顾客签字" width="500px" height="300px" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="handleCloseDialog1">关 闭</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
defineOptions({
  name: "WxKf",
  inheritAttrs: false,
});
import { ElForm } from "element-plus";
// 添加活动标签页响应式变量
import WxKfRecordAPI, {
  WxKfRecordPageVO,
  WxKfRecordForm,
  WxKfRecordPageQuery,
} from "@/api/system/wx-kf-records";
import SignatureCanvas from "@/components/SignatureCanvas/index.vue";

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);
const dataFormRef1 = ref(ElForm);
const signatureRef = ref();

const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);
const kfId = ref<number>();
const reSignture = ref<boolean>(false);

// 添加到现有的响应式变量声明区域
const isViewMode1 = ref(false);

const queryParams = reactive<WxKfRecordPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 客户档案表格数据
const pageData = ref<WxKfRecordPageVO[]>([]);
// 添加到现有的响应式变量声明区域
const visible = ref(false);
// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});
// 弹窗
const dialog2 = reactive({
  title: "",
  visible: false,
});

// 客户档案表单数据
const formData = reactive<WxKfRecordForm>({
  remainNum: 0,
});

// 客户基本资料表单校验规则
const rules = reactive({
  serviceDate: [{ required: true, message: "请输入日期", trigger: "blur" }],
  content: [{ required: true, message: "请输入护理内容", trigger: "blur" }],
  // remainNum: [{ required: true, message: "请输入剩余次数", trigger: "blur" }],
  // amount: [{ required: true, message: "请输入金额", trigger: "blur" }],
  // nurseName: [{ required: true, message: "请输入护理人", trigger: "blur" }],
  // signature: [{ required: true, message: "客户签名不能为空", trigger: "blur" }],
});

// 添加查看对话框的方法
function handleViewDialog(id: number) {
  isViewMode1.value = true;
  handleOpenDialog1(id);
}

/** 打开客户档案弹窗 */
function handleOpenDialog1(id?: number) {
  dialog2.visible = true;
  // 只有当 SignatureCanvas 组件存在时才调用 clearCanvas
  if (signatureRef.value) {
    signatureRef.value.clearCanvas();
  }
  formData.signature = undefined;
  reSignture.value = false;
  if (id) {
    dialog2.title = "护理记录";
    WxKfRecordAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  }
}

/** 关闭客户档案弹窗 */
function handleCloseDialog1() {
  dialog2.visible = false;
  dataFormRef1.value.resetFields();
  dataFormRef1.value.clearValidate();

  formData.id = undefined;
  formData.signature = undefined;
}

/** 查询客户档案 */
function handleQuery() {
  loading.value = true;
  WxKfRecordAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置客户档案查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 打开客户档案弹窗 */
function handleOpenDialog(id?: number) {
  dialog.visible = true;
  // 只有当 SignatureCanvas 组件存在时才调用 clearCanvas
  if (signatureRef.value) {
    signatureRef.value.clearCanvas();
  }
  formData.signature = undefined;
  reSignture.value = false;
  if (id) {
    dialog.title = "编辑护理记录";
    WxKfRecordAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增护理记录";
    // 完全重置表单数据，只保留默认值
    Object.keys(formData).forEach((key) => {
      delete formData[key as keyof WxKfRecordForm];
    });
  }
}

/** 签名完成 */
function handleSignatureChange(value: string) {
  formData.signature = value;
}

/** 重新签名 */
function handleReSignature() {
  reSignture.value = true;
}

/** 提交表单 */
function handleSubmit() {
  // 只有当 SignatureCanvas 组件存在时才调用 saveSignature
  if (signatureRef.value) {
    signatureRef.value.saveSignature();
  }
  dataFormRef.value.validate((valid: boolean) => {
    if (valid) {
      submitFormData();
    }
  });
}

/** 提交表单数据 */
function submitFormData() {
  loading.value = true;
  const id = formData.id;
  if (kfId.value) {
    formData.kfId = kfId.value;
  }
  if (id) {
    WxKfRecordAPI.update(id, formData)
      .then(() => {
        ElMessage.success("编辑成功");
        handleCloseDialog();
        handleResetQuery();
      })
      .finally(() => (loading.value = false));
  } else {
    WxKfRecordAPI.add(formData)
      .then(() => {
        ElMessage.success("新增成功");
        handleCloseDialog();
        handleResetQuery();
      })
      .finally(() => (loading.value = false));
  }
}

/** 关闭客户档案弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();

  formData.id = undefined;
  formData.signature = undefined;
}

/** 删除客户档案 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      WxKfRecordAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

/** 打开护理记录弹窗 */
function openDialog(id: number) {
  queryParams.kfId = id;
  kfId.value = id;
  visible.value = true;
  handleQuery();
}
/** 关闭客户档案弹窗 */
function closeDialog() {
  visible.value = false;
  queryFormRef.value.resetFields();
  queryFormRef.value.clearValidate();
  queryParams.kfId = undefined;
  kfId.value = undefined;
}

// 暴露方法给父组件调用
defineExpose({
  openDialog,
});
</script>

<style scoped>
:deep(.el-input-number .el-input__inner) {
  text-align: left !important;
}

:deep(.el-popper) {
  max-width: 500px;
}
</style>

<style scoped>
.red-text :deep(.el-textarea__inner) {
  color: #2c58e7;
  font-weight: bold;
}

.design-remark {
  margin-top: 20px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.remark-tabs {
  display: flex;
  border-bottom: 1px solid #dcdfe6;
  background-color: #f5f7fa;
}

.tab-item {
  padding: 8px 16px;
  cursor: pointer;
  font-size: 14px;
  color: #606266;
}

.tab-item.active {
  color: #e6a23c;
  font-weight: bold;
  border-bottom: 2px solid #e6a23c;
}

.remark-content {
  padding-top: 0px;
}

.el-textarea__inner {
}
</style>

<style scoped>
.additional-info-title {
  padding: 10px 0;
  border-bottom: 1px solid #dcdfe6;
  margin-bottom: 10px;
  font-weight: bold;
  color: #303133;
  font-size: 14px;
}

/* 确保标题与下方内容有适当的间距 */
.el-form-item {
  margin-bottom: 15px;
}
</style>

<style scoped>
/* 使用 :global 来穿透作用域 */
:global(.custom-title-drawer .el-drawer__header) {
  margin-bottom: -15px;
}

:global(.custom-title-drawer .el-drawer__header span) {
  font-size: 25px !important;
  font-weight: bold !important;
}
</style>
